const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

// 中间件，用于解析JSON数据
app.use(express.json());

// 生成随机密码
function generatePassword(length = 10) {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    return password;
}

// 生成用户名和密码并保存到文件
function generateUserAndPasswordFile() {
    const username = uuidv4();
    const plainPassword = generatePassword();
    bcrypt.hash(plainPassword, 10, (err, hash) => {
        if (err) {
            console.error('Error hashing password:', err);
            return;
        }
        const data = `Username: ${username}\nHashed Password: ${hash}`;
        fs.writeFileSync(path.join(__dirname, 'userCredentials.txt'), data);
        console.log('User credentials generated and saved.');
    });
}

// 监控访问IP和服务器日志
app.use((req, res, next) => {
    const logMessage = `${new Date().toISOString()} - ${req.ip} - ${req.method} ${req.url}\n`;
    fs.appendFileSync(path.join(__dirname,'server.log'), logMessage);
    next();
});

// 生成用户和密码文件（第一次运行时调用）
generateUserAndPasswordFile();

// 读取用户和密码文件
function readUserCredentials() {
    try {
        const data = fs.readFileSync(path.join(__dirname, 'userCredentials.txt'), 'utf8');
        const lines = data.split('\n');
        const username = lines[0].split(': ')[1];
        const hashedPassword = lines[1].split(': ')[1];
        return { username, hashedPassword };
    } catch (err) {
        console.error('Error reading user credentials:', err);
        return null;
    }
}

// 登录验证
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    const credentials = readUserCredentials();
    if (!credentials) {
        return res.json({ success: false, message: 'User credentials not available' });
    }
    bcrypt.compare(password, credentials.hashedPassword, (err, result) => {
        if (err) {
            return res.json({ success: false, message: 'Error during login' });
        }
        if (result && username === credentials.username) {
            res.json({ success: true });
        } else {
            res.json({ success: false, message: 'Invalid username or password' });
        }
    });
});

// 模拟的仪表盘页面（登录成功后访问）
app.get('/dashboard', (req, res) => {
    res.send('Welcome to the Admin Dashboard!');
});

const port = 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});